package com.jiuling.apis.service.balanceService;

import com.jiuling.apis.model.Hmodel.TBaseMerchant;
import com.jiuling.apis.model.Hmodel.basic.TBaseBrand;
import com.jiuling.apis.model.Hmodel.basic.Tbase90DetailLog;
import com.jiuling.apis.model.Hmodel.basic.TbaseDetail;
import com.jswzc.dao.hdao.BaseDaoI;
import com.jswzc.dao.mdao.DaoSupport;
import com.jswzc.framework.util.StringUtil;
import com.jswzc.framework.util.UuidUtil;
import com.jswzc.pay.service.balanceService.BalanceServiceI;
import net.sf.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * Created by qziwm on 2017/6/6.
 */
@Service("balanceService")
public class BalanceServiceImpl implements BalanceServiceI {
    @Resource(name = "daoSupport")
    private DaoSupport dao;
    @Autowired
    private BaseDaoI<TbaseDetail> baseDetailDao;
    @Autowired
    private BaseDaoI<TBaseBrand> basebrandao;
    @Autowired
    private BaseDaoI<Tbase90DetailLog>  baseDetailLogDao;
    @Autowired
    private BaseDaoI<TBaseMerchant>  merchantDao;
    @Override
    public Map<String, Object> operUserCoin90(Map<String, Object> map) throws Exception {
        int userCount= (int) dao.findForObject("BaseUserDao.findUserId",map);
        int userCount2= (int) dao.findForObject("BaseUserDao.findUserCoinId",map);

        Map<String, Object> jSONObject = new HashMap<>();
        //获取消费记录看看这条记录是否重复调用接口
        List<Map<String,String>> checkMap=(List<Map<String, String>>) dao.findForList("BaseUserDao.getbalanceSheet90ByWx", map);
       //获取用户久零贝余额
        Map<String,Object> checkBalance=(Map<String, Object>) dao.findForObject("BaseUserDao.checkUser90Coin", map);
        boolean isBalance=false;//判断用户余额是否足够的参数
        String source=map.get("source").toString();//输入的交易类型
        Double amount=Double.valueOf(map.get("amount").toString());//输入的交易久零贝额
        boolean isHasUser=true;
        if(userCount>0&&userCount2<=0)
        {
            //当有这个用户但是用户不存在久零帐户的时候
            isHasUser=false;
            checkBalance = new HashMap<>();
            checkBalance.put("chargeAmount","0");
            checkBalance.put("giveAmount","0");
        }
        if(checkBalance!=null)
        {
            Double chargeAmount=Double.valueOf(checkBalance.get("chargeAmount").toString());//用户的充值金额
            Double giveAmount=Double.valueOf(checkBalance.get("giveAmount").toString());//用户的赠与金额

            if("2".equals(source))//购买的时候计算总金额够不都
            {
                isBalance=true;//chargeAmount+giveAmount>=amount;//新的逻辑，久零贝不够的时候先扣除，然后返回提示要缴纳多少现金
            }else if("5".equals(source))
            {
                isBalance=chargeAmount>=amount;//提现的时候计算充值金额够不够
            }else if("7".equals(source))
            {
                isBalance=giveAmount>=amount;//手动发券计算充值金额够不够
            }else
            {isBalance=true;}
        }

        if(checkMap!=null&&checkMap.size()>0)
        {
            jSONObject.put("flag", "3");
            jSONObject.put("msg", "操作失败，重复调用");
            return jSONObject;
        }else if(!isBalance)
        {
            jSONObject.put("flag", "2");
            jSONObject.put("msg", "操作失败，余额不足");
            return jSONObject;
        }else
        {
            //开始操作90币
            jSONObject=doOperUserCoin(map,amount,checkBalance,source,isHasUser);
        }
        return jSONObject;
    }


    private Map<String,Object> doOperUserCoin(Map<String, Object> map, Double amount, Map<String, Object> checkBalance, String source,boolean isHasUser) throws Exception {
        Map<String, Object> jSONObject = new HashMap<>();
        String title="";
        if("1".equals(source))//充值
        {
            if(isHasUser) {
                jSONObject = doOperCoin("BaseUserDao.doRechargeCoin", "用户充值", "0", map, "IN");
            }
            else
            {
                map.put("userCoinId",UuidUtil.get32UUID());
                map.put("chargeAmount",map.get("amount"));
                map.put("giveAmount","0");
                jSONObject = doOperCoin("BaseUserDao.doUserCoinSave", "用户充值", "0", map, "IN");
            }
            title= "亲，恭喜你 成功充值了"+map.get("amount")+"元久零贝";
        }else if("2".equals(source))//消费
        {
            Double chargeAmount=Double.valueOf(checkBalance.get("chargeAmount").toString());
            Double giveAmount=Double.valueOf(checkBalance.get("giveAmount").toString());
            Double amoutL=amount;//用于计算的需要消费的金额变量
            Double chargeCut=0.0;//要扣除的充值金额
            Double giveCut=0.0;//要扣除的赠送金额
            Double needMoney=0.0;//要额外缴纳的金额
            if(giveAmount>amount)//全部用赠送金额消费
            {
                giveCut=amount;
                chargeCut=0.0;
                needMoney=0.0;
            }else //赠送金额不够，混合支付
            {
                giveCut=giveAmount;//赠送金额全部扣完;
                amoutL=amoutL-giveCut;//减去赠送金额的钱
                if(amoutL<=chargeAmount)//如果此时充值金额够，直接扣除完毕
                {
                    chargeCut=amoutL;
                    needMoney=0.0;
                }else//否则，全部扣除充值金额并且计算需要缴纳多少现金
                {
                    chargeCut=chargeAmount;
                    amoutL=amoutL-chargeCut;
                    needMoney=amoutL;
                }
            }
            Map<String, Object> map1=new HashMap<>();
            Map<String, Object> map2=new HashMap<>();
            if(giveCut>0)//如果有需要扣除的赠送金额，进行扣除
            {
                map1.put("userId",map.get("userId"));
                map1.put("state",map.get("state"));
                map1.put("orderNum",map.get("orderNum"));
                map1.put("source",map.get("source"));
                map1.put("amount",giveCut);
                jSONObject=doOperCoin("BaseUserDao.doCutCoinGive","用户消费","1",map1,"OUT");
            }
            if(chargeCut>0)//如果有需要扣除的充值金额，进行扣除
            {
                map2.put("userId",map.get("userId"));
                map2.put("state",map.get("state"));
                map2.put("orderNum",map.get("orderNum"));
                map2.put("source",map.get("source"));
                map2.put("amount",chargeCut);
                jSONObject=doOperCoin("BaseUserDao.doCutCoin","用户消费","0",map2,"OUT");
            }
            jSONObject.put("flag", "0");
            jSONObject.put("msg", "操作成功");
            jSONObject.put("needMoney",needMoney);
            title= "亲，恭喜你 成功消费了"+(giveCut+chargeCut)+"元久零贝";
        }else if("3".equals(source))//赠送
        {
            if(isHasUser) {
                jSONObject=doOperCoin("BaseUserDao.doGiveCoin","赠送久零贝","1",map,"IN");
            }
            else
            {
                map.put("userCoinId",UuidUtil.get32UUID());
                map.put("giveAmount",map.get("amount"));
                map.put("chargeAmount","0");
                jSONObject = doOperCoin("BaseUserDao.doUserCoinSave", "赠送久零贝", "1", map, "IN");
            }
            title= "亲，恭喜你 赠送了"+map.get("amount")+"元久零贝";
        }else if("4".equals(source))//退款
        {/*
            Map<String, Object> map1=new HashMap<>();
            Map<String, Object> map4=new HashMap<>();
            Map<String, Object> map6=new HashMap<>();
            Map<String, Object> map2= (Map<String, Object>) dao.findForObject("BaseUserDao.findSheetByMap",map);
            Map<String, Object> map3= (Map<String, Object>) dao.findForObject("BaseUserDao.findSheetByMapGive",map);
            Map<String, Object> map5= (Map<String, Object>) dao.findForObject("BaseUserDao.findSheetByMapExtra",map);
            Double amounttk=0.0;
            if(map2!=null) {
                map1.put("userId", map.get("userId"));
                map1.put("state", map.get("state"));
                map1.put("orderNum", map.get("orderNum"));
                map1.put("source", map.get("source"));
                map1.put("amount", map2.get("amount"));
                amounttk+=Double.valueOf(map2.get("amount").toString());
                jSONObject = doOperCoin("BaseUserDao.doRechargeCoin", "用户退款", "0", map1,"IN");
            }
            if(map3!=null) {

                map4.put("userId", map.get("userId"));
                map4.put("state", map.get("state"));
                map4.put("orderNum", map.get("orderNum"));
                map4.put("source", map.get("source"));
                map4.put("amount", map3.get("amount"));
                amounttk+=Double.valueOf(map3.get("amount").toString());
                jSONObject = doOperCoin("BaseUserDao.doGiveCoin", "用户退款", "1", map4,"IN");
            }	if(map5!=null) {
            map6.put("userId", map.get("userId"));
            map6.put("state", map.get("state"));
            map6.put("orderNum", map.get("orderNum"));
            map6.put("source", map.get("source"));
            map6.put("amount", map5.get("amount"));
            amounttk+=Double.valueOf(map5.get("amount").toString());
            jSONObject = doOperCoin("BaseUserDao.doGiveCoinExtra", "用户退款", "2", map4,"IN");
        }
            if(map2==null&&map3==null&&map5==null)
            {
                jSONObject.put("flag", "0");
                jSONObject.put("msg", "操作成功，不需要退币");
            }
            *//******************向用户发送模板消息************************//*
            title= "亲，恭喜你 成功退款"+amounttk+"元久零贝";*/

   /*         Map<String, Object> map1=new HashMap<>();
            map1.put("userId", map.get("userId"));
            map1.put("state", map.get("state"));
            map1.put("orderNum", map.get("orderNum"));
            map1.put("source", map.get("source"));
            map1.put("amount",amount);*/

             //新的退款逻辑是全部退赠送金额，所以前面的先注释掉
            if(isHasUser) {
                jSONObject = doOperCoin("BaseUserDao.doGiveCoin", "用户退款", "1", map,"IN");
            }
            else
            {
                map.put("userCoinId",UuidUtil.get32UUID());
                map.put("giveAmount",map.get("amount"));
                map.put("chargeAmount","0");
                jSONObject = doOperCoin("BaseUserDao.doUserCoinSave", "用户退款", "1", map, "IN");
            }
        }else if("5".equals(source))//提现
        {
            jSONObject=doOperCoin("BaseUserDao.doCutCoin","用户提现","0",map,"OUT");
            title= "亲，恭喜你 成功提现"+map.get("amount")+"元久零贝";
        }else if("6".equals(source))//提现
        {
            jSONObject=doOperCoin("BaseUserDao.doRechargeCoin","提现失败退回","0",map,"IN");
            title= "亲，提现审核未通过，"+map.get("amount")+"元久零贝已经返回您的余额";
        }
        else if("7".equals(source))//手动发券撤回
        {
            Map<String, Object> map2= (Map<String, Object>) dao.findForObject("BaseUserDao.findSheetByGive",map);
            Double amountGive= Double.valueOf(map2.get("amount").toString());
            if(Math.abs(amount-amountGive)<0.001)
            {
                jSONObject=doOperCoin("BaseUserDao.doCutCoinGive","发券撤回","1",map,"OUT");
                title= "亲，久零券发放撤回，赠送的"+map.get("amount")+"元久零贝已经从您的余额扣除";
            }
            else{
                jSONObject.put("flag", "1");
                jSONObject.put("msg", "金额不对，撤回失败");
            }
        }
        jSONObject.put("title",title);
        return jSONObject;
    }


    private Map<String, Object> doOperCoin(String sql, String note, String type, Map<String,Object> map, String inOut) throws Exception {
        Map<String, Object> jSONObject = new HashMap<>();
        int res=(int) dao.update(sql, map);
        if(res>0)
        {

            String id= UuidUtil.get32UUID();
            String serialNum=/*"JN_"+inOut+"_"+*/getRndNumCode()+"";
            map.put("id",id);
            map.put("serialNum",serialNum);
            map.put("note",note);
            map.put("type",type);
            dao.save("BaseUserDao.saveSheet90", map);
            jSONObject.put("flag", "0");
            jSONObject.put("msg", "操作成功");
        }
        else
        {
            jSONObject.put("flag", "1");
            jSONObject.put("msg", "操作失败,找不到open_id对应用户");
        }
        return  jSONObject;
    }
    public long getRndNumCode()
    {
        Random rand = new Random();
        Date now = new Date();
        long t = now.getTime();
        return Long.valueOf(t * 1000L + (long)rand.nextInt(1000));
    }




    @Override
    public Map<String, Object> updateUserBalance90(Map<String, Object> map) throws Exception {
        JSONObject jSONObject = new JSONObject();
        List<Map<String,String>> checkMap=(List<Map<String, String>>) dao.findForList("BaseUserDao.getUserDetail90ByWx", map);//获取流水记录防止重复调用
        Map<String,Object> user=(Map<String, Object>) dao.findForObject("BaseUserDao.getUserBalanceByOpenId", map);//获取用户id和剩余久零券
        Map<String,Object> userMain=(Map<String, Object>) dao.findForObject("BaseUserDao.getUserByOpenId", map);//获取用户id和剩余久零券
        TBaseBrand brand=null;
        String brandCode=map.get("brand_code")+"";
        if(!StringUtil.isNullOrEmpty(brandCode))
        {brand=basebrandao.getById(TBaseBrand.class,brandCode);}
        Date expiryTime=null;
        if(brand!=null){
            map.put("sorts",brand.getSorts());
        }else
        {
            map.put("sorts",99);
        }
        String source=map.get("source").toString();
        String state=map.get("state").toString();
        Double amount=Double.valueOf(map.get("balance_90").toString());
        boolean isBalance=false;
        boolean isBalanceOK=true;
        if(user!=null)
        {
            String userBalance=user.get("balance_90").toString();
            double balance_90=Double.parseDouble(userBalance);
            double balance_90Main=Double.parseDouble(userMain.get("balance_90")+"");
            if("1".equals(state))//如果是要支出久零券的，校验是否够
            {
                map.put("point90Now",0);
                isBalance=balance_90>=amount;
                if(Math.abs(balance_90Main-balance_90)>0.01)
                { isBalanceOK=false;}
                map=doForBalance90Total(state,source,map);
            }else{
                map.put("point90Now",amount);
                isBalance=true;
                map=doForBalance90Total(state,source,map);
                expiryTime=doGetExpiryTime(brand,map); //获取90券的时候读取商户信息获得过期时间
            }
            map.put("expiryTime",expiryTime);
        }
        if("2".equals(source))//如果是手动发券的，需要计算商户的余额够不够
        { isBalance=checkBrandBalance(amount,brand);}
        if(!isBalanceOK)
        {
            jSONObject.put("flag", "4");
            jSONObject.put("msg", "操作失败，发券记录与用户余额不匹配");
            dao.update("BaseUserDao.updateUserForBalance90Wrong",map);
            return jSONObject;
        }
        if(checkMap!=null&&checkMap.size()>0)
        {
            jSONObject.put("flag", "3");
            jSONObject.put("msg", "操作失败，重复调用");
            return jSONObject;
        }else if(!isBalance)
        {
            jSONObject.put("flag", "2");
            jSONObject.put("msg", "操作失败，余额不足");
            return jSONObject;
        }
        else
        {
            String mainId= map.get("order_code")+"";
            if("3".equals(source)){
                int res=doOperBalanceForConsume(user,map,mainId);//当为消费久零券的时候，进行久零券的消券操作
                if(res<0)//消费处理失败，直接返回失败
                {
                    jSONObject.put("flag", "2");
                    jSONObject.put("msg", "操作失败，没有加券记录用于消费");
                    throw new Exception("操作失败，没有加券记录用于消费");
                }
            }
            if("5".equals(source)){
                int res=doOperBalanceForRefundsNew(user,map,mainId);//当为退款退券的时候，单独处理
                if(res<0)//消费处理失败，直接返回失败
                {
                    jSONObject.put("flag", "2");
                    jSONObject.put("msg", "操作失败，没有加券记录用于消费");
                    throw new Exception("操作失败，没有加券记录用于消费");
                }
                map.put("point90Now",res);
            }
            if("9".equals(source)||"10".equals(source)) {//单独处理撤回
                jSONObject = doCancalNew(map.get("order_code") + "", user, source,mainId);
                if(!"0".equals(jSONObject.get("flag")))
                {throw new Exception("");}
            }
            dao.update("BaseUserDao.operBalance90ByWx", map);//修改用户余额
            map.put("userId",user.get("id"));
            dao.save("BaseUserDao.saveDetail90ByWx", map);//插入流水记录
            jSONObject.put("flag", "0");
            jSONObject.put("msg", "操作成功");
            if("2".equals(source))//手动发券的时候操作商户的久零券余额
            { doUpdateBrandBalance90(amount,brand);}
        }
        return jSONObject;
    }



    private Map<String,Object> doForBalance90Total(String state, String source, Map<String, Object> map) {
        if(!"1".equals(state)&&!"5".equals(source))//当退款的时候，不增加总额
        {
            map.put("balance_90Total",map.get("balance_90"));
        }else
        {
            map.put("balance_90Total",0);
        }
        if("1".equals(state)&&("9".equals(source)||"10".equals(source)))//当撤回的时候，需要撤回总额
        {
            map.put("balance_90Total",map.get("balance_90"));
        }else
        {
            map.put("balance_90Total",0);
        }
        return map;
    }

    private void doUpdateBrandBalance90(Double amount, TBaseBrand brand) {
        if(brand!=null)
        {
            if(brand.getBalance90()>amount)
            {brand.setBalance90((long) (brand.getBalance90()-amount));}
            else
            {
                brand.setCreditNow90((int) (amount-brand.getBalance90()));
                brand.setBalance90((long) 0);
            }
            basebrandao.update(brand);
        }
    }

    private boolean checkBrandBalance(Double amount, TBaseBrand brand) {
        boolean isBalance=false;
        if(brand!=null) {
            if (amount > brand.getBalance90() + brand.getCreditTotal90() - brand.getCreditNow90()) {
                isBalance = false;
            } else {
                isBalance = true;
            }
        }else
        {
            isBalance = false;
        }
        return isBalance;
    }

    private Date doGetExpiryTime(TBaseBrand brand, Map<String, Object> map) throws ParseException {
        SimpleDateFormat sdfTime = new SimpleDateFormat(
                "yyyy-MM-dd HH:mm:ss");
        Date expiryTime=sdfTime.parse(laterDate(new Date(),365));
        int expiryDateType=2;
        if(brand!=null)
        {expiryDateType=brand.getExpiryDateType();}
        if(StringUtil.isNullOrEmpty(expiryDateType)||!StringUtil.isNumeric(expiryDateType+""))
        {
            expiryDateType=2;
        }
        Date grantTime=new Date();
        try{
            grantTime=getGrantTime(map);
        }
        catch (Exception e)
        {
            e.getMessage();
        }
        String expiryTimeString=getExpiryTime(grantTime,expiryDateType);
        if(!StringUtil.isNullOrEmpty(expiryTimeString))
        {

            expiryTime=sdfTime.parse(expiryTimeString);
        }
        else
        {
            expiryTime=sdfTime.parse(laterDate(new Date(),365));
        }
        return  expiryTime;
    }


    private Date getGrantTime(Map<String, Object> map) throws Exception {
        String source=map.get("source").toString();
        String sourceId=map.get("order_code").toString();
        String type=map.get("type").toString();
        String grantString="";
        if("2".equals(source))//手动发券
        {
            grantString= (String) dao.findForObject("OrderDao.getCreateTimeByMainCodeSD",sourceId);
        }
        else if("4".equals(source))//实体卡
        {
            grantString= (String) dao.findForObject("OrderDao.getCreateTimeByCardCodeSTK",sourceId);
        }
        else if("1".equals(source))//自动发券
        {
            if("2".equals(type))//微商城的查询微商城表，其他查询联盟订单表
            {
                grantString= (String) dao.findForObject("OrderDao.getCreateTimeByCode",sourceId);
            }
            else
            {
                grantString= (String) dao.findForObject("OrderDao.getCreateTimeByMainCodeZD",sourceId);
            }
        }
        if(StringUtil.isNullOrEmpty(grantString)) {
            return new Date();
        }
        else
        {
            DateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            return format.parse(grantString);
        }

    }

    private String getExpiryTime(Date grantTime,int expiryDateType) {
        String dateString="";
        switch (expiryDateType)
        {
            case 1:dateString=laterDate(grantTime,90);break;
            case 2:dateString=laterDate(grantTime,365);break;
            case 3:dateString=laterDate(grantTime,1095);break;
            default:dateString=laterDate(grantTime,365);break;
        }
        return  dateString;
    }
    public  String laterDate(Date grantTime,int days) {
        DateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date temp_date = null;
        try {
            Calendar c = Calendar.getInstance();
            c.setTime(grantTime);
            c.add(Calendar.DATE, days);
            temp_date = c.getTime();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return format.format(temp_date);
    }


    private int doOperBalanceForConsume(Map<String, Object> user, Map<String, Object> map,String id) {

        String hql=StringUtil.formateString("from TbaseDetail t where t.openId='{0}' and t.point90Now>0 and t.state=0 and t.isdel=0 and t.inOuts=1 order by t.sorts asc, t.expireTime asc",map.get("open_id")+"");
        List<TbaseDetail> baseDetailList=baseDetailDao.find(hql);

        Integer amount=Integer.valueOf(map.get("balance_90").toString());
        if(baseDetailList.size()<=0)//如果没有找到加券记录，返回-1
        {return -1;}
        else//否则对记录按照顺序循环操作
        {
            for(TbaseDetail detail:baseDetailList)
            {
                if(amount<=0)
                {break;}
                Tbase90DetailLog log=new Tbase90DetailLog();
                log.setType(0);
                log.setOrderId(id);
                log.setSourceId(detail.getId());

                if(detail.getPoint90Now().intValue()>=amount)
                {
                    log.setPoint90(amount);
                    detail.setPoint90Now(detail.getPoint90Now()-amount);
                    baseDetailDao.update(detail);
                    baseDetailLogDao.save(log);
                    break;
                }
                else
                {
                    log.setPoint90(detail.getPoint90Now());
                    amount=amount-detail.getPoint90Now();
                    detail.setPoint90Now(0);
                    baseDetailDao.update(detail);
                    baseDetailLogDao.save(log);
                }
            }
        }
        return 1;
    }

    private JSONObject doCancalNew(String order_code, Map<String, Object> user,String source,String id) throws Exception {
        JSONObject jSONObject = new JSONObject();
        String userBalance=user.get("balance_90").toString();
        int balance_90=Integer.parseInt(userBalance);
        /**以下进行预处理，判断是否够退券**/
        TbaseDetail td=baseDetailDao.getById(TbaseDetail.class,order_code);
        if ((td!=null)&&(td.getIsdel()==0))
        {
            if(td.getPoint90()>balance_90)
            {
                jSONObject.put("flag", "2");
                jSONObject.put("msg", "操作失败，余额不足");
                return jSONObject;
            }

            Map<String,Object> map=new HashMap<>();
            map.put("balance_90",td.getPoint90());
            map.put("open_id",td.getOpenId());


            /**以下处理对商户进行退券**/
            if(source.equals("9")) {
                TBaseBrand brand = basebrandao.getById(TBaseBrand.class, td.getBrandId());
                if (brand.getCreditNow90() >= td.getPoint90()) {
                    brand.setCreditNow90(brand.getCreditNow90() - td.getPoint90());
                } else if (brand.getCreditNow90() > 0) {
                    brand.setBalance90(brand.getBalance90() + td.getPoint90() - brand.getCreditNow90());
                    brand.setCreditNow90(0);
                } else {
                    brand.setBalance90(brand.getBalance90() + td.getPoint90());
                }
                basebrandao.update(brand);
            }
            /**以下处理对用户进行退券**/
            //  int res=(int) dao.update("BaseUserDao.cancalBalance90ByWx", map);

            if(td.getPoint90Now()>=td.getPoint90())//当该笔记录的余额没有消费的时候，直接扣除,完成退券
            {
                Tbase90DetailLog log=new Tbase90DetailLog();
                log.setType(1);
                log.setOrderId(id);
                log.setSourceId(td.getId());
                log.setPoint90(td.getPoint90());
                td.setPoint90Now(td.getPoint90Now()-td.getPoint90());
                baseDetailLogDao.save(log);

            }else{
                int amount=td.getPoint90()-td.getPoint90Now();//当余额不足的时候，先扣该笔记录，然后从其他记录扣券
                Tbase90DetailLog log=new Tbase90DetailLog();
                log.setType(1);
                log.setOrderId(id);
                log.setSourceId(td.getId());
                log.setPoint90(td.getPoint90Now());
                td.setPoint90Now(0);
                baseDetailLogDao.save(log);

                String hql=StringUtil.formateString("from TbaseDetail t where t.openId='{0}' and t.point90Now>0 and t.state=0 and t.isdel=0 and t.inOuts=1 order by t.expireTime asc",map.get("open_id")+"");
                List<TbaseDetail> baseDetailList=baseDetailDao.find(hql);
                if(baseDetailList.size()<=0)//如果没有找到加券记录，返回-1
                {  jSONObject.put("flag", "2");
                    jSONObject.put("msg", "操作失败，余额不足");
                }
                else//否则对记录按照顺序循环操作
                {
                    for(TbaseDetail detail:baseDetailList)
                    {
                        if(amount<=0)
                        {break;}
                        log=new Tbase90DetailLog();
                        log.setType(1);
                        log.setOrderId(id);
                        log.setSourceId(detail.getId());

                        if(detail.getPoint90Now()>=amount&&!detail.getId().equals(td.getId()))
                        {
                            log.setPoint90(amount);
                            detail.setPoint90Now(detail.getPoint90Now()-amount);
                            baseDetailDao.update(detail);
                            baseDetailLogDao.save(log);
                            break;
                        }
                        else if(!detail.getId().equals(td.getId()))
                        {
                            log.setPoint90(detail.getPoint90Now());
                            amount=amount-detail.getPoint90Now();
                            detail.setPoint90Now(0);
                            baseDetailDao.update(detail);
                            baseDetailLogDao.save(log);
                        }
                    }
                }
            }

            td.setIsdel(1);
            td.setCancelTime(new Date());
            baseDetailDao.update(td);
            jSONObject.put("flag", "0");
            jSONObject.put("msg", "操作成功");

        }else
        {
            jSONObject.put("flag", "1");
            jSONObject.put("msg", "操作失败,找不到对应的发券记录");
            return jSONObject;
        }

        return jSONObject;
    }

    private int doOperBalanceForRefundsNew(Map<String, Object> user, Map<String, Object> map,String id) throws Exception {

        List<Map<String,Object>> list= (List<Map<String,Object>>) dao.findForList("OrderDao.getLogByOrderId",map);
        if(list.size()<=0)
        {throw  new Exception("没有找到对应的消费记录");}
        Integer amount=Integer.valueOf(map.get("balance_90").toString());
        for(Map<String,Object> log:list)
        {
            Integer point=Integer.valueOf(log.get("point90")+"");
            TbaseDetail detail =baseDetailDao.getById(TbaseDetail.class,log.get("sourceId")+"");
            Tbase90DetailLog detailLog=new Tbase90DetailLog();
            detailLog.setType(2);
            detailLog.setOrderId(id);
            detailLog.setSourceId(detail.getId());

            if(point>=amount)
            {
                detail.setPoint90Now(detail.getPoint90Now()+amount);
                detailLog.setPoint90(amount);
                amount=0;

            }else
            {
                detail.setPoint90Now(detail.getPoint90Now()+point);
                amount=amount-point;
                detailLog.setPoint90(point);
            }
            baseDetailDao.update(detail);
            baseDetailLogDao.save(detailLog);
            if(amount<=0)
            {break;}
        }
        return amount;

    }
    @Override
    public Map<String, Object> updateMerchantBalance(Map<String, Object> map) throws Exception {
        Map<String,Object> resMap=new HashMap<>();
        Double balance=0.0;
        String state=map.get("state")+"";
        try{ balance=Double.valueOf(map.get("balance")+"");}
        catch (Exception e)
        {   resMap.put("code","1");
            resMap.put("errorCode","1002");
            resMap.put("errorMsg","参数异常错误");
            return  resMap;
        }

        TBaseMerchant merchant=merchantDao.getById(TBaseMerchant.class,map.get("merchantId").toString());
        if(merchant==null)
        {
            resMap.put("code","1");
            resMap.put("errorCode","1011");
            resMap.put("errorMsg","没有该商户");
            return  resMap;
        }
        if("1".equals(state)&&merchant.getBalance()<balance){
            resMap.put("code","1");
            resMap.put("errorCode","1010");
            resMap.put("errorMsg","余额不足");
        }else
        {
            if("1".equals(state))
            {
                merchant.setBalance(merchant.getBalance()-balance);
            }else
            {
                merchant.setBalance(merchant.getBalance()+balance);
                merchant.setBalanceTotal(merchant.getBalanceTotal()+balance);
            }
            merchantDao.update(merchant);
            map.put("id",UuidUtil.get32UUID());
            dao.save("MerchantDao.saveBalanceLog",map);
            resMap.put("code","0");
        }
        return resMap;
    }
}
